package com.example.service.impl;

import ch.qos.logback.classic.Logger;
import com.example.entity.*;
import com.example.entity.maintenance.HydpressHalfMon;
import com.example.entity.maintenance.HydpressHalfYear;
import com.example.entity.maintenance.HydpressQuarter;
import com.example.entity.maintenance.HydpressYear;
import com.example.ext.entity.ExtSysUser;
import com.example.ext.entity.maintenance.ExtHydpressDto;
import com.example.ext.entity.maintenance.ExtHydpressHalfMon;
import com.example.mapp.*;
import com.example.service.HydpressService;
import com.example.util.PromotionUtil;
import com.example.util.ResultUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by douyx on 2017/10/29.
 */
@Service
public class HydpressServiceImpl implements HydpressService {

	private final static Logger logger = (Logger) LoggerFactory.getLogger(HydpressServiceImpl.class);

	@Autowired
	private HydpressMapp hydpressMapp;

	@Autowired
	private MessageNoticeMapp messageNoticeMapp;

	@Autowired
	private PromotionMapp promotionMapp;
	
	@Autowired
	private ElevatorMapp elevatorMapp;

	@Autowired
	private MaintUserAddedMapp maintUserAddedMapp;

	@Autowired
	private AfterDoMapp afterDoMapp;

	/**
	 * 新增液压电梯维保数据
	 * 
	 * @param hydpress
	 *            液压电梯维保数据
	 * @return
	 */
	@Override
	@Transactional
	public Map<String, Object> addHydpress(ExtHydpressDto hydpress) {
		try {
			// 获取液压电梯半月保数据
			HydpressHalfMon halfMon = hydpress.getHydpressHalfMon();
			if (null == halfMon) {
				throw new Exception("无液压电梯维保数据!");
			}
			// 添加液压电梯半月保数据,并获取半月保ID
			halfMon.setChangeInfo(hydpress.getChangeInfo());
			halfMon.setSummary(hydpress.getSummary());
			hydpressMapp.addHydpressHalfMon(halfMon);

			// 获取液压电梯季度保数据
			//添加推送消息
			MessageNotice messageNotice = new MessageNotice();
			messageNotice.setElevatoriType("2");
			String conten = "("+hydpress.getHydpressHalfMon().getElevatorNum()+")电梯的 ";
			Integer empiricValue = 0;
			String addedItem = "";
			if(hydpress.getHydpressHalfMon().getType().equals("1")){
				conten+="半月保 于"+hydpress.getHydpressHalfMon().getMaintenanceEndDate()+" 完成，请去确认签字。维保人员:"+hydpress.getUserNameCn();
				empiricValue = 10;
				addedItem = "提交1份半月保记录";
				addEmpiric(halfMon, empiricValue, addedItem, false, 0);
			}
			if(hydpress.getHydpressHalfMon().getType().equals("2")){
				conten+="季度保 于"+hydpress.getHydpressHalfMon().getMaintenanceEndDate()+" 完成，请去确认签字。维保人员:"+hydpress.getUserNameCn();
				empiricValue = 20;
				addedItem = "提交1份季度保记录";
				addEmpiric(halfMon, empiricValue, addedItem, true, 4);
			}
			if(hydpress.getHydpressHalfMon().getType().equals("3")){
				conten+="半年保 于"+hydpress.getHydpressHalfMon().getMaintenanceEndDate()+" 完成，请去确认签字。维保人员:"+hydpress.getUserNameCn();
				empiricValue = 30;
				addedItem = "提交1份半年保记录";
				addEmpiric(halfMon, empiricValue, addedItem, true, 2);
			}
			if(hydpress.getHydpressHalfMon().getType().equals("4")){
				conten+="年保 于"+hydpress.getHydpressHalfMon().getMaintenanceEndDate()+" 完成，请去确认签字。维保人员:"+hydpress.getUserNameCn();
				empiricValue = 50;
				addedItem = "提交1份年保记录";
				addEmpiric(halfMon, empiricValue, addedItem, true, 1);
			}
			if (halfMon.getXcfhcs() != null) {
				addEmpiric(halfMon, 5, "落实现场安全防护措施”拍照上传1次", false, 0);
			}
			List<MaintUserAdded> maintUserAddedList = hydpress.getMaintUserAddedList();
			if (null != maintUserAddedList && maintUserAddedList.size() > 0) {
				for (MaintUserAdded tmp : maintUserAddedList) {

					if(null!=tmp.getMaintContent()&& !"".equals(tmp.getMaintContent())){
						tmp.setHalfMonId(halfMon.getId()+"");
						maintUserAddedMapp.add(tmp);
					}
				}
				addEmpiric(halfMon, 2 * maintUserAddedList.size(), "提交的维保记录中（不限类型），有增加的维保项目", false, 0);
			}
			messageNotice.setTitle("维保完成通知");
			messageNotice.setContent(conten);
			messageNotice.setElevatoriMonId(halfMon.getId().toString());
			messageNotice.setIsRead("0");
			messageNotice.setNoticeTime(hydpress.getHydpressHalfMon().getMaintenanceEndDate());
			messageNotice.setReceivePartyId(hydpress.getReceivePartyId());
			messageNotice.setSendUserId(hydpress.getSendUserId());
			messageNotice.setReceiveUserId(hydpress.getReceiveUserId());
			messageNoticeMapp.add(messageNotice);

			Elevator elevator = elevatorMapp.queryByElevatorNum(halfMon.getElevatorNum());
			elevator.setMaintenanceUserFirst(Long.valueOf(halfMon.getMaintenanceUserId1()));
			elevator.setMaintenanceUserSecond(Long.valueOf(halfMon.getMaintenanceUserId2()));
			elevatorMapp.update(elevator);

			HydpressQuarter quarter = hydpress.getHydpressQuarter();
			if (null == quarter) {
				try{
					AfterDo afterDo = new AfterDo();
					afterDo.setEventType("1");
					afterDo.setStatus("1");
					AfterDo afterDo1 = afterDoMapp.findByType(afterDo);
					return ResultUtil.returnSuccess("成功", afterDo1);
				}catch (Exception e){
					logger.error("查询维保场景失败",e);
				}
				return ResultUtil.returnSuccess("成功", null);
			}
			quarter.setHalfMonId(halfMon.getId());
			// 添加液压电梯季度保数据,并获取季度ID
			hydpressMapp.addHydpressQuarter(quarter);
			// 获取液压电梯半年保数据
			HydpressHalfYear halfYear = hydpress.getHydpressHalfYear();
			if (null == halfYear) {
				try{
					AfterDo afterDo = new AfterDo();
					afterDo.setEventType("1");
					afterDo.setStatus("1");
					AfterDo afterDo1 = afterDoMapp.findByType(afterDo);
					return ResultUtil.returnSuccess("成功", afterDo1);
				}catch (Exception e){
					logger.error("查询维保场景失败",e);
				}
				return ResultUtil.returnSuccess("成功", null);
			}
			halfYear.setQuarterId(quarter.getId());
			// 添加液压电梯半年保数据,并获取半年保
			 hydpressMapp.addHydpressHalfYear(halfYear);
			// 获取液压电梯年保数据
			HydpressYear year = hydpress.getHydpressYear();
			if (null == year) {
				try{
					AfterDo afterDo = new AfterDo();
					afterDo.setEventType("1");
					afterDo.setStatus("1");
					AfterDo afterDo1 = afterDoMapp.findByType(afterDo);
					return ResultUtil.returnSuccess("成功", afterDo1);
				}catch (Exception e){
					logger.error("查询维保场景失败",e);
				}
				return ResultUtil.returnSuccess("成功", null);
			}
			year.setHalfYearId(halfYear.getId());
			hydpressMapp.addHydpressYear(year);

			try{
				AfterDo afterDo = new AfterDo();
				afterDo.setEventType("1");
				afterDo.setStatus("1");
				AfterDo afterDo1 = afterDoMapp.findByType(afterDo);
				return ResultUtil.returnSuccess("成功", afterDo1);
			}catch (Exception e){
				logger.error("查询维保场景失败",e);
			}
			return ResultUtil.returnSuccess("成功", null);

		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			logger.error(e.getMessage());
			return ResultUtil.returnError(e.getMessage(), null);
		}
	}

	private void addEmpiric(HydpressHalfMon halfMon, Integer empiricValue, String content, boolean flag, Integer times) throws Exception {
		/*try {
			Elevator elevator = elevatorMapp.queryByElevatorNum(halfMon.getElevatorNum());
			int realTimes1 = 0;
			int realTimes2 = 0;
			if (flag) {
				Map<String, Object> param1 = new HashMap<>();
				param1.put("userId", elevator.getMaintenanceUserFirst());
				param1.put("type", "4");
				param1.put("addedTime", new SimpleDateFormat("yyyy").format(new Date()));
				param1.put("type", content);
				realTimes1 = promotionMapp.findAddTimes(param1);

				Map<String, Object> param2 = new HashMap<>();
				param2.put("userId", elevator.getMaintenanceUserSecond());
				param2.put("type", "4");
				param2.put("addedTime", new SimpleDateFormat("yyyy").format(new Date()));
				param2.put("type", content);
				realTimes2 = promotionMapp.findAddTimes(param2);
			}
			if (elevator.getMaintenanceUserFirst() != null && (!flag || times >= realTimes1)) {
				Map<String, Object> map = new HashMap<>();
				map.put("type", "4");
				map.put("userId", elevator.getMaintenanceUserFirst());
				Promotion promotion2 = promotionMapp.findById(map);
				if (null != promotion2 && promotion2.getId() != null) {
					promotion2 = PromotionUtil.calc(promotion2, "4", empiricValue, false);
					promotionMapp.update(promotion2);
				} else {
					promotion2 = new Promotion();
					promotion2.setType("4");
					promotion2.setUserId(elevator.getMaintenanceUserFirst().toString());
					promotion2 = PromotionUtil.calc(promotion2, "4", empiricValue, true);
					promotionMapp.insert(promotion2);
				}
				PromotionRecord promotionRecord = new PromotionRecord();
				promotionRecord.setUserId(promotion2.getUserId());
				promotionRecord.setType(promotion2.getType());
				promotionRecord.setEmpiricItem(content);
				promotionRecord.setAddedTime(PromotionUtil.getTime());
				promotionRecord.setEmpiricValue(empiricValue);
				promotionMapp.insertRecord(promotionRecord);
			}
			if (elevator.getMaintenanceUserSecond() != null && (!flag || times >= realTimes2)) {
				Map<String, Object> map = new HashMap<>();
				map.put("type", "4");
				map.put("userId", elevator.getMaintenanceUserSecond());
				Promotion promotion2 = promotionMapp.findById(map);
				if (null != promotion2 && promotion2.getId() != null) {
					promotion2 = PromotionUtil.calc(promotion2, "4", empiricValue, false);
					promotionMapp.update(promotion2);
				} else {
					promotion2 = new Promotion();
					promotion2.setType("4");
					promotion2.setUserId(elevator.getMaintenanceUserSecond().toString());
					promotion2 = PromotionUtil.calc(promotion2, "4", empiricValue, true);
					promotionMapp.insert(promotion2);
				}
				PromotionRecord promotionRecord = new PromotionRecord();
				promotionRecord.setUserId(promotion2.getUserId());
				promotionRecord.setType(promotion2.getType());
				promotionRecord.setEmpiricItem(content);
				promotionRecord.setAddedTime(PromotionUtil.getTime());
				promotionRecord.setEmpiricValue(empiricValue);
				promotionMapp.insertRecord(promotionRecord);
			}
		}catch(Exception e){
			logger.error(e.getMessage(), e);
		}*/
	}
	
	/**
	 * 获取液压电梯维保数据
	 * 
	 * @param hydpress
	 * @return
	 */
	@Override
	public Map<String, Object> queryHydpress(ExtHydpressHalfMon hydpress) {
		List<ExtHydpressHalfMon> list = null;
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			Page<ExtSysUser> page = PageHelper.startPage(hydpress.getCurrentPage(), hydpress.getPageSize());
			list = hydpressMapp.findHydpressList(hydpress);
			map.put("list", list);
			map.put("total", page.getTotal());

		} catch (Exception e) {
			logger.error(e.getMessage());
			return ResultUtil.returnError(e.getMessage(), null);
		}
		return ResultUtil.returnSuccess("成功", map);
	}

	/**
	 * 获取液压电梯维保详细数据
	 * 
	 * @param id
	 * @return
	 */
	@Override
	public Map<String, Object> queryHydpressDetails(String id) {
		ExtHydpressDto hydpress = new ExtHydpressDto();
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			HydpressHalfMon hydpressHalfMon = hydpressMapp.queryHydpressHalfMon(id);
			hydpress.setHydpressHalfMon(hydpressHalfMon);
			HydpressQuarter hydpressQuarter = hydpressMapp.queryHydpressQuarter(id);
			if (hydpressQuarter == null) {
				map.put("hydpress", hydpress);
				return ResultUtil.returnSuccess("成功", map);
			}
			hydpress.setHydpressQuarter(hydpressQuarter);
			HydpressHalfYear hydpressHalfYear = hydpressMapp.queryHydpressHalfYear(hydpressQuarter.getId());
			if (hydpressHalfYear == null) {
				map.put("hydpress", hydpress);
				return ResultUtil.returnSuccess("成功", map);
			}
			hydpress.setHydpressHalfYear(hydpressHalfYear);
			hydpress.setHydpressYear(hydpressMapp.queryHydpressYear(hydpressHalfYear.getId()));
			hydpress.setMaintUserAddedList(maintUserAddedMapp.queryList(id + ""));
			map.put("hydpress", hydpress);
		} catch (Exception e) {
			logger.error(e.getMessage());
			return ResultUtil.returnError(e.getMessage(), null);
		}
		return ResultUtil.returnSuccess("成功", map);
	}
}
